package IC.lir;

import java.util.LinkedList;
import java.util.Vector;
import java.util.HashMap;

public class ClassStructure {
	
	private HashMap<String, Integer> _fieldsOffsets = new HashMap<String, Integer>(),
									_functionsOffSets = new HashMap<String, Integer>();
	private Vector<String> _dispatchVector;

	public ClassStructure(String classID, ClassStructure extendedClass, LinkedList<IC.AST.ClassField> fields, LinkedList<IC.AST.Method> methods)
	{
		_fieldsOffsets.putAll(extendedClass._fieldsOffsets);
		InsertFields(fields);
		
		_functionsOffSets.putAll(extendedClass._functionsOffSets);
		_dispatchVector = new Vector<String>(extendedClass._dispatchVector);
		InsertMethods(methods, classID);
	}
	
	public ClassStructure(String classID, LinkedList<IC.AST.ClassField> fields, LinkedList<IC.AST.Method> methods)
	{
		_dispatchVector = new Vector<String>();
		InsertFields(fields);
		InsertMethods(methods, classID);
	}
	
	private void InsertFields(LinkedList<IC.AST.ClassField> fields)
	{
		int lastIndex = _fieldsOffsets.size() + 1;
		for (IC.AST.ClassField method : fields)
			_fieldsOffsets.put(method.GetID(), lastIndex++);
	}
	
	private void InsertMethods(LinkedList<IC.AST.Method> methods, String classID)
	{
		for (IC.AST.Method method : methods)
		{
			if (method.IsStatic())
				continue;
			Integer searched;
			String methodLabel = String.format("_%s_%s", classID, method.GetID());
			if ((searched = _functionsOffSets.get(method.GetID())) == null)
			{
				_functionsOffSets.put(method.GetID(), _functionsOffSets.size());
				_dispatchVector.add(methodLabel);
			}
			else
				_dispatchVector.set(searched.intValue(), methodLabel);			
		}
	}
	
	public String StringDispatchContent()
	{
		String ret = "[";
		for (String function : _dispatchVector)
			ret += function + ",";
		
		return ret.substring(0, ret.length() - ((ret.length() != 1) ? 1 : 0)) + "]";
	}
	
	public int GetFieldIndex (String field) { return _fieldsOffsets.get(field); }
	public int GetMethodIndex (String method) { return _functionsOffSets.get(method); }
	public int GetClassSize() { return _fieldsOffsets.size() + 1; }
}
